<?php
namespace app\api\controller\agent;

use think\Controller;
use think\Request;
use think\Db;
use app\common\model\power\Rolepower;
use app\common\model\user\User as UserModel;
use app\api\controller\Base;
use think\facade\Env;
use app\api\controller\Pub;
class Orders extends Base
{
    public function initialize()
    {
        parent::initialize();
        $this->is_login();
        Rolepower::powerguard('303004'); // 订单管理权限
    }

    private function is_login()
    {
        $data =UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }

    //产品列表
    public function productList()
    {
        $devices = Db::name('device')->field('id,name')->where('id','>',1)->select();
        $accessories = Db::name('accessories')->select();
        $productMap = [];
        foreach ($devices as $device) {
            $device['accessories'] = [];
            $productMap[$device['id']] = $device;
        }
        foreach ($accessories as $accessory) {
            $deviceId = $accessory['device_id'];
            if (isset($productMap[$deviceId])) {
                $productMap[$deviceId]['accessories'][] = $accessory;
            }
        }
        $result = array_values($productMap);
        return myok($result);
    }

    //拆单
    public function productOrder(Request $request)
    {
        $data = $request->post();
        // 验证必要参数
        if (empty($data['contract_id']) || empty($data['devices_id']) || empty($data['accessories_id']) || empty($data['customer_id'])) {
            return json(['code' => 0, 'msg' => '参数不完整']);
        }

        // 确保设备ID和配件ID是数组（处理可能的字符串格式）
        if (!is_array($data['devices_id'])) {
            $data['devices_id'] = explode(',', $data['devices_id']);
        }
        if (!is_array($data['accessories_id'])) {
            $data['accessories_id'] = explode(',', $data['accessories_id']);
        }

        // 获取设备信息（逐个处理）
        $devices = Db::name('device')
            ->whereIn('id', $data['devices_id'])
            ->select();
        
        // 检查设备是否存在
        $deviceIds = array_column($devices, 'id');
        $invalidIds = array_diff($data['devices_id'], $deviceIds);
        if (!empty($invalidIds)) {
            return json(['code' => 0, 'msg' => '设备ID不存在：' . implode(',', $invalidIds)]);
        }

        // 获取配件信息并构建设备ID到配件的映射（每个设备关联的配件）
        $accessories = Db::name('accessories')
            ->whereIn('id', $data['accessories_id'])
            ->select();
        
        $deviceAccessoriesMap = [];
        foreach ($accessories as $accessory) {
            $deviceId = $accessory['device_id'];
            $deviceAccessoriesMap[$deviceId][] = $accessory['id'];
        }

        // 生成流量卡订单
        $cardCount = Db::name('device')
            ->whereIn('id', $data['devices_id'])
            ->where('is_need', 1)
            ->count();
        
        $cardData = [
            'contract_id' => $data['contract_id'],
            'customer_id' => $data['customer_id'],
            'accessories_id' => 1,
            'device_id' => 1, 
            'factory_id' => 1, 
            'status' => 1,
            'create_time' => time(),
            'update_time' => time(),
            'remark' => $cardCount . '张'
        ];
        $cardOrderId = Db::name('contract_order')->insertGetId($cardData);

        // 为每个设备生成独立订单
        $currentTime = time();
        $orderIds = [];

        try {
            Db::startTrans(); // 开启事务

            foreach ($devices as $device) {
                $deviceId = $device['id'];
                $factoryId = $device['factory_id'];

                // 当前设备关联的配件ID
                $accessoryIds = $deviceAccessoriesMap[$deviceId] ?? [];

                // 准备订单数据（单个设备）
                $orderData = [
                    'contract_id' => $data['contract_id'],
                    'device_id' => $deviceId, 
                    'accessories_id' => !empty($accessoryIds) ? implode(',', $accessoryIds) : '',
                    'factory_id' => $factoryId,
                    'customer_id' => $data['customer_id'],
                    'track_number' => $data['track_number'] ?? '',
                    'status' => 1,
                    'create_time' => $currentTime,
                    'update_time' => $currentTime
                ];

                // 插入单个设备的订单
                $orderId = Db::name('contract_order')->insertGetId($orderData);
                $orderIds[] = $orderId;
            }

            array_unshift($orderIds, $cardOrderId);

            Db::commit(); // 提交事务
            return json([
                'code' => 1, 
                'msg' => '生成订单成功', 
                'order_ids' => $orderIds,
                'order_count' => count($orderIds) // 订单总数（含流量卡）
            ]);
        } catch (\Exception $e) {
            Db::rollback(); // 回滚事务
            return json(['code' => 0, 'msg' => '生成订单失败：' . $e->getMessage()]);
        }
    }

    //订单列表
    public function orderList(Request $request)
    {
    // 分页参数处理（强制转换为整数，避免非数值错误）
        $page = (int)($request->get('page') ?? 1);
        $pageSize = (int)($request->get('pageSize') ?? 10);
        $keyword = $request->get('keyword'); // 物流单号

        $pub = new Pub();
        $user_id = $pub->userid();
        $role = Db::name('user')->where('UserId', $user_id)->value('Role');
        
        // 获取客户ID列表（权限控制）
        $customer_ids = [];
        if ($role == 303) { // 代理商管理员
            $agency_id = Db::name('user_agency')->where('user_id', $user_id)->value('agency_id');
            $emp_ids = Db::name('user_agency')->where('agency_id', $agency_id)->column('user_id');
            $customer_ids = Db::name('user_customer')->whereIn('user_id', $emp_ids)->column('customer_id');
        } elseif ($role == 304) { // 代理商员工
            $customer_ids = Db::name('user_customer')->where('user_id', $user_id)->column('customer_id');
        } else {
            return json(['code' => 0, 'msg' => '权限不足']);
        }
        
        if (empty($customer_ids)) {
            return json(['code' => 1, 'msg' => 'success', 'data' => []]);
        }
        
        // 执行分页查询（修正分页参数格式）
        $ordersPaginate = Db::name('contract_order')
            ->alias('o')
            ->join('product_contract c', 'o.contract_id = c.id', 'LEFT')
            ->join('customer cu', 'o.customer_id = cu.CustomerId', 'LEFT')
            ->join('factory f','f.id=o.factory_id')
            ->whereIn('o.customer_id', $customer_ids)
            ->when($keyword, function ($query) use ($keyword) {
                $query->where('o.track_number', 'like', "%{$keyword}%");})
            ->order('o.create_time desc')
            ->field([
                'o.*',
                'f.name as factory_name',
                'c.name as contract_name',
                'c.img_url as contract_img_url',
                'cu.Name as customer_name',
                'cu.Address as customer_address',
                'cu.Tel as customer_tel'
            ])
            ->paginate([
                'page' => $page,
                'list_rows'=>$pageSize,
            ]); 

            $orderList = $ordersPaginate->toArray()['data'];

            if (!empty($orderList)) {
                // 1. 收集所有设备ID和配件ID
                $allDeviceIds = [];
                $allAccessoryIds = [];
                foreach ($orderList as $order) {
                    // 设备ID
                    $deviceIds = explode(',', $order['device_id'] ?? '');
                    $allDeviceIds = array_merge($allDeviceIds, $deviceIds);
                    // 配件ID
                    if (!empty($order['accessories_id'])) {
                        $accessoryIds = explode(',', $order['accessories_id']);
                        $allAccessoryIds = array_merge($allAccessoryIds, $accessoryIds);
                    }
                }

                // 2. 批量查询设备信息（键为设备ID）
                $deviceMap = [];
                if (!empty($allDeviceIds)) {
                    $devices = Db::name('device')
                        ->whereIn('id', $allDeviceIds)
                        ->field('id, name')
                        ->select();
                    foreach ($devices as $dev) {
                        $deviceMap[$dev['id']] = $dev;
                    }
                }

                // 3. 批量查询配件信息（并按设备ID分组）
                $accessoryMap = [];
                if (!empty($allAccessoryIds)) {
                    $accessories = Db::name('accessories')
                        ->whereIn('id', $allAccessoryIds)
                        ->select();
                    foreach ($accessories as $acc) {
                        $deviceId = $acc['device_id'] ?? 0;
                        $accessoryMap[$deviceId][] = $acc;
                    }
                }

                // 4. 处理每条订单数据
                foreach ($orderList as &$order) {
                    // 设备信息（关联批量查询的结果）
                    $deviceIds = explode(',', $order['device_id'] ?? '');
                    $devices = [];
                    foreach ($deviceIds as $id) {
                        if (isset($deviceMap[$id])) {
                            $devices[] = $deviceMap[$id];
                        }
                    }
                    // 为设备绑定配件
                    foreach ($devices as &$dev) {
                        $dev['accessories'] = $accessoryMap[$dev['id']] ?? [];
                    }
                    unset($dev); 

                
                    $order['create_time'] = date('Y-m-d H:i:s', $order['create_time'] ?? time());
                    $order['update_time'] = date('Y-m-d H:i:s', $order['update_time'] ?? time());


                    $order['device'] = $devices;
                    unset($order['device_id'], $order['accessories_id']);
                }
                unset($order);
            }

            $result = $ordersPaginate->toArray();
            $result['data'] = $orderList;

            return json(['code' => 1, 'msg' => 'success', 'data' => $result]);
    }

    //订单状态修改
    public function orderStatusChange(Request $request)
    {
        $data = $request->post();
        if (empty($data['id']) || empty($data['track_number']) || empty($data['status'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $order = Db::name('contract_order')->where('id', $data['id'])->find();
        if (!$order) {
            return json(['code'=>0, 'msg'=>'订单不存在']);
        }
        Db::name('contract_order')->where('id', $data['id'])->update([
            'track_number' => $data['track_number'],
            'status' => $data['status'],
            'update_time' => time()
        ]);
        return json(['code'=>1, 'msg'=>'修改成功']);
    }

    //有客户信息和合同信息的订单列表
    /*public function orderList(Request $request)
    {
        $page = $request->get('page');
        $pageSize=$request->get('pageSize');
        $keyword = $request->get('keyword');
        $pub = new Pub();
        $user_id = $pub->userid();
        $role = Db::name('user')->where('UserId', $user_id)->value('Role');
        
        // 获取客户ID列表
        if ($role == 303) { // 代理商管理员
            $agency_id = Db::name('user_agency')->where('user_id', $user_id)->value('agency_id');
            $emp_ids = Db::name('user_agency')->where('agency_id', $agency_id)->column('user_id');
            $customer_ids = Db::name('user_customer')->whereIn('user_id', $emp_ids)->column('customer_id');
        } elseif ($role == 304) { // 代理商员工
            $customer_ids = Db::name('user_customer')->where('user_id', $user_id)->column('customer_id');
        } else {
            return json(['code' => 0, 'msg' => '权限不足']);
        }
        
        if (empty($customer_ids)) {
            return json(['code' => 1, 'msg' => 'success', 'data' => []]);
        }
        
        $orders = Db::name('contract_order')
            ->alias('o')
            ->join('product_contract c', 'o.contract_id = c.id', 'LEFT')
            ->join('customer cu', 'o.customer_id = cu.CustomerId', 'LEFT')
            ->whereIn('o.customer_id', $customer_ids)
            ->order('create_time desc')
            ->field([
                'o.*',
                'c.name as contract_name',    // 合同名称
                'c.img_url as contract_img_url', // 合同凭证
                'cu.Name as customer_name',   // 客户姓名
                'cu.Address as customer_address', // 客户地址
                'cu.Tel as customer_tel'      // 客户电话
            ])
            ->select();

        foreach ($orders as &$order) {
            $order['device'] = Db::name('device')
                ->whereIn('id', explode(',', $order['device_id']))
                ->field('id, name')
                ->select();
            
            $accessories = isset($order['accessories_id']) 
                ? Db::name('accessories')->whereIn('id', explode(',', $order['accessories_id']))->select() 
                : [];
            
            $accessoriesByDevice = [];
            foreach ($accessories as $acc) {
                $accessoriesByDevice[$acc['device_id']][] = $acc;
            }
            foreach ($order['device'] as &$dev) {
                $dev['accessories'] = $accessoriesByDevice[$dev['id']] ?? [];
            }
            unset($dev);
            unset($order['device_id'], $order['accessories_id']);
            $order['create_time'] = date('Y-m-d H:i:s', $order['create_time']);
            $order['update_time'] = date('Y-m-d H:i:s', $order['update_time']);
        }
        
        return json(['code' => 1, 'msg' => 'success', 'data' => $orders]);
    }*/

    /*
    public function productOrder(Request $request)
    {
        $data = $request->post();
        // 验证必要参数
        if (empty($data['contract_id']) || empty($data['devices_id']) || empty($data['accessories_id']) || empty($data['customer_id'])) {
            return json(['code' => 0, 'msg' => '参数不完整']);
        }
    
        // 获取设备信息并按 factory_id 分组
        $devices = Db::name('device')
            ->whereIn('id', $data['devices_id'])
            ->select();
        
        //生成流量卡订单,
        //流量卡数量()
        $card_count=Db::name('device')->whereIn('id', $data['devices_id'])->where('is_need',1)->count();
        $cardData['contract_id']=$data['contract_id'];
        $cardData['customer_id']=$data['customer_id'];
        $cardData['accessories_id']=1;
        $cardData['device_id']=1;
        $cardData['factory_id']=1;
        $cardData['status']=1;
        $cardData['create_time']=time();
        $cardData['update_time']=time();
        $cardData['remark']=$card_count.'张';
        $cardOrderId=Db::name('contract_order')->insertGetId($cardData);

        if (count($devices) != count($data['devices_id'])) {
            return json(['code' => 0, 'msg' => '部分设备ID不存在']);
        }
        // 按 factory_id 分组设备
        $devicesByFactory = [];
        foreach ($devices as $device) {
            $factoryId = $device['factory_id'];
            $devicesByFactory[$factoryId][] = $device;
        }
        
        // 获取配件信息并构建设备ID到配件的映射
        $accessories = Db::name('accessories')
            ->whereIn('id', $data['accessories_id'])
            ->select();
        
        $deviceAccessoriesMap = [];
        foreach ($accessories as $accessory) {
            $deviceAccessoriesMap[$accessory['device_id']][] = $accessory['id'];
        }
        
        // 为每个 factory_id 创建订单
        $currentTime = time();
        $orderIds = [];
        
        try {
            Db::startTrans(); // 开启事务
            
            foreach ($devicesByFactory as $factoryId => $factoryDevices) {
                // 当前厂商的设备ID
                $factoryDeviceIds = array_column($factoryDevices, 'id');
                
                // 当前设备组的所有配件ID
                $factoryAccessoryIds = [];
                foreach ($factoryDeviceIds as $deviceId) {
                    if (isset($deviceAccessoriesMap[$deviceId])) {
                        $factoryAccessoryIds = array_merge($factoryAccessoryIds, $deviceAccessoriesMap[$deviceId]);
                    }
                }
                
                // 准备订单数据
                $orderData = [
                    'contract_id' => $data['contract_id'],
                    'device_id' => implode(',', $factoryDeviceIds), 
                    'accessories_id' => implode(',', array_unique($factoryAccessoryIds)),
                    'factory_id' => $factoryId,
                    'customer_id' => $data['customer_id'],
                    'track_number' => $data['track_number'] ?? '',
                    'status' => 1,
                    'create_time' => $currentTime,
                    'update_time' => $currentTime
                ];
                
                // 插入订单并记录订单ID
                $orderId = Db::name('contract_order')->insertGetId($orderData);
                $orderIds[] = $orderId;
                
            }
            //将流量卡的订单ID加入到订单ID中。
            array_unshift($orderIds,$cardOrderId);
            Db::commit(); // 提交事务
            
            return json(['code' => 1, 'msg' => '生成订单成功', 'order_ids' => $orderIds]);
        } catch (\Exception $e) {
            Db::rollback(); // 回滚事务
            return json(['code' => 0, 'msg' => '生成订单失败：' . $e->getMessage()]);
        }
    }
*/
    /*只有订单信息的订单列表
    public function orderList(Request $request)
    {
        $pub=new Pub();
        $user_id=$pub->userid();
        $role= Db::name('user')->where('UserId', $user_id)->value('Role');
        if($role == 303){//代理商管理员
            $agency_id=Db::name('user_agency')->where('user_id',$user_id)->value('agency_id');
            $emp_ids = Db::name('user_agency')->where('agency_id',$agency_id)->column('user_id');
            $customer_ids=Db::name('user_customer')->whereIn('user_id',$emp_ids)->column('customer_id');
        }elseif($role == 304){//代理商员工  
            $customer_ids=Db::name('user_customer')->where('user_id',$user_id)->column('customer_id');
        }

        $orders = Db::name('contract_order')->whereIn('customer_id', $customer_ids)->select();
        foreach ($orders as &$order) {
            $order['device'] = Db::name('device')->whereIn('id', explode(',', $order['device_id']))->field('id,name')->select();
            $order['accessories'] = isset($order['accessories_id']) ? Db::name('accessories')->whereIn('id', explode(',', $order['accessories_id']))->select() : [];
            $order['create_time'] = date('Y-m-d H:i:s', $order['create_time']);
            $order['update_time'] = date('Y-m-d H:i:s', $order['update_time']);
 
            // 按device_id分组配件
            $accessoriesByDevice = [];
            foreach ($order['accessories'] as $acc) {
                $accessoriesByDevice[$acc['device_id']][] = $acc;
            }
            // 给每个设备加上accessories字段
            foreach ($order['device'] as &$dev) {
                $dev['accessories'] = isset($accessoriesByDevice[$dev['id']]) ? $accessoriesByDevice[$dev['id']] : [];
            }
            //删除不必要的字段
            unset($dev);
            unset($order['accessories']);
            unset($order['device_id']);
            unset($order['accessories_id']);
        }
        return json(['code'=>1, 'msg'=>'success', 'data'=>$orders]);
    }
    */
} 